<?php
/**
 * Created by PhpStorm.
 * User: CZT
 * Date: 2020/7/2
 * Time: 9:04
 */

namespace app\admin\controller;


use app\reuse\controller\ResponseJson;
use app\service\IGeTuiService;
use app\service\jobService;
use app\service\MemberCode;
use app\service\MemberService;
use app\service\ResourceService;
use Redis\Redis;
use think\App;
use think\Db;

/**
 * 玩家管理
 * Class Member
 * @package app\admin\controller
 */
class Member extends Common
{
    use ResponseJson;

    function __construct(App $app = null)
    {
        parent::__construct();
    }

    /**
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 玩家列表
     */
    function index()
    {
        if (input('get.action') != 'ajax') {
            $this->assign('mark', input('get.mark'));
            $this->assign('address', input('get.address'));
            $this->assign('level', input('get.level'));
            $this->assign('age', input('get.age'));
            $this->assign('team', input('get.teamId'));
            $this->assign("checkmark",input("get.checkmark"));
            $this->assign("checklevel",input("get.checklevel"));
            $this->assign('canUseLevel',input("get.canUseLevel"));
            $this->assign('lanunchdetail',input("get.lanunchdetail"));
            $this->assign('team_id',input("get.team_id"));
            return $this->fetch();
        } else {
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 10;
            }
            # 定义where
            $_where = 'm.id !=0 ';
            # 接收筛选条件
            $mark = input('post.mark');
            if (!empty($mark)) {
                if ($mark == 'memberNewTodayNum') {
                    # 今日新增用户
                    $_where = "date(m.register_time) = '" . date('Y-m-d') . "' and m.fictitious != 1";
                } elseif ($mark == 'memberExitedNum') {
                    # 已退出玩家
                    $_where = "m.type in (3,4) and m.fictitious != 1";
                } elseif ($mark == 'men') {
                    # 男玩家
                    $_where = "m.sex=1 and m.fictitious != 1";
                } elseif ($mark == 'women') {
                    # 女玩家
                    $_where = "m.sex=2 and m.fictitious != 1";
                } elseif ($mark == 'address') {
                    # 地区
                    $_where = "m.address='" . input('post.address') . "' and m.fictitious != 1";
                } elseif ($mark == 'level') {
                    # 等级
                    $_where = "m.level = " . input('post.level') . " and m.fictitious != 1";
                } elseif ($mark == 'age') {
                    # 年龄
                    $age = explode(',', input('post.age'));
                    if (!empty($age[1])) {
                        $_where = "(m.age >= " . $age[0] . " and m.age < " . $age[1] . ") and m.fictitious != 1";
                    } else {
                        $_where = "m.age >= " . $age[0] . " and m.fictitious != 1";
                    }
                } elseif ($mark == 'team') {
                    # 团队
                    $_where = "m.team_id = " . input('post.team') . " and m.fictitious != 1 and status = 5";
                }
            }
            # 搜索条件
            $searchParams = json_decode(input('post.searchParams'), true);
            if (!empty($searchParams)) {
                # 姓名/手机号/ID搜索
                if (!empty($searchParams['searchInfo'])) {
                    $_where .= " and (m.name like '%" . $searchParams['searchInfo'] . "%'
                     or m.code like '%" . $searchParams['searchInfo'] . "%' 
                     or m.phone like '%" . $searchParams['searchInfo'] . "%') and m.fictitious != 1";
                }
                # 时间筛选
                if (!empty($searchParams['register_min'])) {
                    $_where .= " and date(m.register_time) >= '" . $searchParams['register_min'] . "' and m.fictitious != 1";
                }
                if (!empty($searchParams['register_max'])) {
                    $_where .= " and date(m.register_time) <= '" . $searchParams['register_max'] . "' and m.fictitious != 1";
                }
                # 等级筛选
                if (!empty($searchParams['level'])) {
                    $_where .= " and m.level in (" . $searchParams['level'] . ") and m.fictitious != 1";
                }
                # 团队筛选
                if (!empty($searchParams['team_id'])) {
                    $_where .= " and m.team_id in (" . $searchParams['team_id'] . ") and m.fictitious != 1";
                }
                # 状态筛选
                if (!empty($searchParams['type'])) {
                    if ($searchParams['type'] == 5) {
                        # 未赠送状态筛选
                        $_where .= " and m.giving_status=1 and m.status=5 and m.fictitious != 1";
                    } elseif ($searchParams['type'] == 6) {
                        # 已赠送状态筛选
                        $_where .= " and m.giving_status=2 and m.status=5  and m.fictitious != 1";
                    } else {
                        $_where .= " and m.type = " . $searchParams['type'] . " and m.fictitious != 1";
                    }
                }
                # 虚拟用户筛选
                if (!empty($searchParams['fictitious']) or $searchParams['fictitious'] === '0') {
                    $_where .= " and m.fictitious = " . $searchParams['fictitious'];
                }
                # 收益筛选
                if (!empty($searchParams['income'])) {
                    if ($searchParams['income'] == '60000.0') {
                        $_where .= " and mp.income > " . intval($searchParams['income']) . " and m.fictitious != 1";
                    } else {
                        $_where .= " and mp.income <= " . intval($searchParams['income']) . " and m.fictitious != 1";
                    }
                }
                # 违规次数筛选
                if (!empty($searchParams['infraction'])) {
                    $infraction = explode(',', $searchParams['infraction']);
                    if (!empty($infraction[1])) {
                        $_where .= " and (m.infraction >= " . $infraction[0] . " and m.infraction < " . $infraction[1] . ") and m.fictitious != 1";
                    } else {
                        $_where .= " and m.infraction >= " . $infraction[0] . " and m.fictitious != 1";
                    }
                }
                # 性别筛选
                if (!empty($searchParams['sex'])) {
                    $_where .= " and m.sex=" . $searchParams['sex'] . " and m.fictitious != 1";
                }
                # 年龄筛选
                if (!empty($searchParams['age'])) {
                    $age = explode(',', $searchParams['age']);
                    if (!empty($age[1])) {
                        $_where .= " and (m.age >= " . $age[0] . " and m.age < " . $age[1] . ") and m.fictitious != 1";
                    } else {
                        $_where .= " and m.age >= " . $age[0] . " and m.fictitious != 1";
                    }
                }
                # 地区筛选
                if (!empty($searchParams['province'])) {
                    $_where .= " and m.province='" . $searchParams['province'] . "' and m.fictitious != 1";
                }
                if (!empty($searchParams['city'])) {
                    $_where .= " and m.city='" . $searchParams['city'] . "' and m.fictitious != 1";
                }
                if (!empty($searchParams['area'])) {
                    $_where .= " and m.area='" . $searchParams['area'] . "' and m.fictitious != 1";
                }
                # button 筛选
                if (!empty($searchParams['buttonHidden'])) {
                    # 全部用户
                    if ($searchParams['buttonHidden'] == 'countNum') {
                        $_where = 'm.id !=0 ';
                    } # 已激活
                    elseif ($searchParams['buttonHidden'] == 'activated') {
                        $_where = "m.id !=0 and m.status = 5 and m.fictitious != 1";
                    } # 虚拟用户
                    elseif ($searchParams['buttonHidden'] == 'fictitious') {
                        $_where = 'm.id !=0 and m.fictitious = 1';
                    } #未激活
                    elseif ($searchParams['buttonHidden'] == 'notActive') {
                        $_where = 'm.id !=0 and m.status != 5 and m.fictitious != 1';
                    } #未赠送
                    elseif ($searchParams['buttonHidden'] == 'notGiving') {
                        $_where = 'm.id !=0 and m.giving_status=1 and m.status=5 and m.fictitious != 1';
                    }
                }
            }
            $lanunchdetail=input("get.lanunchdetail");
            if(!empty($lanunchdetail)){
                # 需购买筛选
                $checkmark=input("get.checkmark");
                $checklevel=input("get.checklevel");
                $canUseLevel=input("get.canUseLevel");
                $team_id= input("get.team_id");
                $_mapping="";
                if(!empty($team_id)){
                    $_mapping = " and m.team_id = {$team_id}";
                }
                if($checkmark==1){
                    # 需购买数量
                        $_where = " m.id in (select m.id from member_business_grid mbg,member m left join team t on m.team_id = t.id where m.code = mbg.member_code and m.fictitious!=1
                         and mbg.status in (1,3) and mbg.member_business_id = 0  and m.level in ({$canUseLevel}) {$_mapping} group by mbg.member_code)";
                }elseif($checkmark==2){
                    # 出售中数量
                    $_where = " m.id in (select m.id from member_business mb,member m left join team t on m.team_id = t.id where m.code=mb.member_code and mb.status=3  and m.fictitious!=1
                    and mb.earnings_level = {$checklevel} and mb.lanunch=1 {$_mapping} group by mb.member_code)";
                }elseif($checkmark==3){
                    # 待出售数量
                    $_where = " m.id in (select m.id from member_business mb,member m left join team t on m.team_id = t.id where m.code=mb.member_code 
                    and mb.status in (1,2,4)  and mb.earnings_level = {$checklevel} {$_mapping} group by mb.member_code)";
                }else{
                    # 匹配中用户
                    $_where = " m.id in (select m.id from member_business_grid mbg,member m left join team t on m.team_id = t.id where m.code = mbg.member_code and m.fictitious!=1
                         and mbg.status = 4 and mbg.member_business_id = 0  and m.level in ({$canUseLevel}) {$_mapping} group by mbg.member_code)";
                }
            }
            # 查询列表
            $info = Db::table('member m')
                ->field("m.*,ml.title levelTitle,t.title teamTitle,mc.wx_number,ali_number,unionpay_number,mp.income,
                mp.ruby,mp.materials,mp.integral,mp.gold,t.team_num,m.giving_status,
                (select count(id) from member_business_grid where m.code=member_code and status = 1 and member_business_id=0 
                and start_time < '" . date('Y-m-d H:i:s', strtotime('- 24 hours')) . "') activeState")
                ->join('member_level ml', 'ml.level=m.level', 'left')
                ->join('team t', 't.id=m.team_id and t.is_fake=1', 'left')
                ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                ->join('member_property mp', 'mp.member_code=m.code and mp.is_fake=1', 'left')
                ->where($_where)
                ->order(array('id' => 'desc'))
                ->paginate($listRows, false, ['query' => request()->param()]);

            # 列表统计
            # 已激活
            $activated = Db::table('member m')
                ->join('member_level ml', 'ml.level=m.level', 'left')
                ->join('team t', 't.id=m.team_id and t.is_fake=1', 'left')
                ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                ->join('member_property mp', 'mp.member_code=m.code and mp.is_fake=1', 'left')
                ->where($_where . ' and m.status=5 and m.fictitious != 1')
                ->count('m.id');
            # 虚拟用户
            $fictitious = Db::table('member m')
                ->join('member_level ml', 'ml.level=m.level', 'left')
                ->join('team t', 't.id=m.team_id and t.is_fake=1', 'left')
                ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                ->join('member_property mp', 'mp.member_code=m.code and mp.is_fake=1', 'left')
                ->where($_where . ' and  m.fictitious = 1')
                ->count('m.id');
            # 未激活
            $notActive = Db::table('member m')
                ->join('member_level ml', 'ml.level=m.level', 'left')
                ->join('team t', 't.id=m.team_id and t.is_fake=1', 'left')
                ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                ->join('member_property mp', 'mp.member_code=m.code and mp.is_fake=1', 'left')
                ->where($_where . ' and m.status!=5 and m.fictitious != 1')
                ->count('m.id');
            # 未赠送
            $notGiving = Db::table('member m')
                ->join('member_level ml', 'ml.level=m.level', 'left')
                ->join('team t', 't.id=m.team_id and t.is_fake=1', 'left')
                ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                ->join('member_property mp', 'mp.member_code=m.code and mp.is_fake=1', 'left')
                ->where($_where . ' and m.status=5 and m.giving_status=1 and m.fictitious != 1')
                ->count('m.id');
            # 收益总额
            $total = Db::table('member m')
                ->field('IFNULL(sum(mp.income),0) incomeTotal,IFNULL(sum(mp.gold),0) goldTotal,IFNULL(sum(mp.integral),0) integralTotal')
                ->join('member_level ml', 'ml.level=m.level', 'left')
                ->join('team t', 't.id=m.team_id and t.is_fake=1', 'left')
                ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                ->join('member_property mp', 'mp.member_code=m.code and mp.is_fake=1', 'left')
                ->where($_where)
                ->where("m.fictitious != 1")
                ->find();
            # 返回数据
            return $this->jsonSuccessData(array('info' => $info, 'statistics' => array('activated' => $activated, 'fictitious' => $fictitious, 'notActive' => $notActive, 'total' => $total, "notGiving" => $notGiving)));
        }
    }


    /**
     * @return string
     * @throws \think\exception\DbException
     * @content 查询玩家等级
     */
    function memberLevelInfo()
    {
        if (input('get.action') == 'ajax') {
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 15;
            }
            # where 条件
            $where = '';
            # 名称搜索
            $title = input('post.title');
            if (!empty($title)) {
                $where = " ml.title like '%" . $title . "%'";
            }
            # 查询信息
            $info = Db::table('member_level ml')
                ->field('title,level')
                ->where($where)
                ->order(array('ml.level' => 'asc'))
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($info);
        }
    }

    /**
     * @return string
     * @throws \think\exception\DbException
     * @content 团队信息
     */
    function teamInfo()
    {
        if (input('get.action') == 'ajax') {
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 10;
            }
            # where 条件
            $where = 'is_fake=1';
            # 名称搜索
            $title = input('post.title');
            if (!empty($title)) {
                $where .= " and title like '%" . $title . "%'";
            }
            # 查询信息
            $info = Db::table('team')
                ->field('id,title,team_num,team_earnings income')
                ->where($where)
                ->order(array('id' => 'desc'))
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($info);
        }
    }

    /**
     * @return array|mixed
     * @throws \BaseException
     * @throws \think\Exception
     * @content 添加用户
     */
    function add()
    {
        if (input('get.action') != 'ajax') {
            return $this->fetch();
            Session("source_upload", null);
        } else {
            # 执行添加
            $info = input('post.');
            $info['address'] = $info['province'] . $info['city'] . $info['area'];
            # 判断手机号重复
            $phoneInfo = Db::table('member')->field('id')->where(array('phone' => $info['phone']))->find();
            if (!empty($phoneInfo)) {
                return array('status' => false, 'msg' => '手机号重复');
            }
            # 无用图片清理
            $delImg = array_filter(array($info['head_portrait'], $info['idcard'], $info['ali_img'], $info['wx_img']));
            if (!empty($delImg)) {
                ResourceService::delCacheItem($delImg);
                ResourceService::delUploadCache();
            }
            # 获取code
            $code = MemberCode::getMemberCode('', $info['team_id']);
//            $info['team_id'] = $code['team_id'];
            $code = $code['code'];
            $info['code'] = $code;
            $info['status'] = 3;
            $info['fictitious'] = 1;
            $collection = array(
                'member_code' => $code,
                'wx_number' => $info['wx_number'],
                'ali_number' => $info['ali_number'],
                'unionpay_number' => $info['unionpay_number'],
                'bank' => $info['bank'],
                'bank_people' => $info['bank_people'],
                'bank_address' => $info['bank_address'],
                'ali_img' => $info['ali_img'],
                'wx_img' => $info['wx_img'],
            );
            unset($info['headImg'], $info['idcardImg'],
                $info['wx_number'], $info['ali_number'], $info['unionpay_number'],
                $info['bank'], $info['bank_people'], $info['bank_address'], $info['ali_img'], $info['wx_img']
            );
            # 添加信息
            $res = Db::table('member')->insert($info);
            if ($res) {
                # 添加收款信息
                Db::table('member_collection')->insert($collection);
                # 财产
                Db::table('member_property')->insert(array('member_code' => $code));
            }
            # 修改redis
            MemberService::changeRedis($code);
            return array('status' => true);
        }
    }

    /**
     * @return array|mixed
     * @throws \BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 玩家修改
     */
    function write()
    {
        if (input('get.action') != 'ajax') {
            if (input('get.action') != 'delete') {
                Session("source_upload", null);
                $id = input('get.code');
                if (!empty($id)) {
                    # 查询用户信息
                    $info = Db::table('member m')
                        ->field("m.*,ml.title levelTitle,t.title teamTitle,
                        mc.wx_number,ali_number,unionpay_number,wx_img,ali_img,bank,bank_people,bank_address,
                        mp.income,mp.ruby,mp.materials,mp.integral,mp.gold,
                        (select count(id) from member_business_grid where m.code=member_code and status = 1 and member_business_id=0 
                and start_time < '" . date('Y-m-d H:i:s', strtotime('- 24 hours')) . "') activeState")
                        ->join('member_level ml', 'ml.level=m.level', 'left')
                        ->join('team t', 't.id=m.team_id and t.is_fake=1', 'left')
                        ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                        ->join('member_property mp', 'mp.member_code=m.code and mp.is_fake=1', 'left')
                        ->where(array('m.code' => $id))
                        ->find();
                    $info['team_num'] = Db::table('member')->field('code')
                        ->where("code != '" . $info['code'] . "'")
                        ->where("(code in ((select code from member where p_code in 
            (select code from member where p_code in(select code from member where p_code = '" . $info['code'] . "'))),
            (select code from member where p_code in(select code from member where p_code = '" . $info['code'] . "')),
            (select code from member where p_code = '" . $info['code'] . "')))")
                        ->count();
                    $this->assign('info', $info);
                    return $this->fetch();
                }
            } else {
                # 删除玩家
                $memberCode = input('post.memberCode');
                Db::table('member')->where(array('code' => $memberCode))->update(array('type' => 3));
                return array('status' => true);
            }
        } else {
            # 执行修改
            # 用户基本信息
            $info = input('post.info');
            # 用户收款信息
            $collection = input('post.collection');
            # 用户财产
            $property = input('post.property');
            # 用户财产原有数据
            $property_old = input('post.property_old');
            # 用户ID
            $code = input('post.code');
            # 修改之前的团队
            $old_teamId = $info['old_team_id'];
            unset($info['old_team_id']);
            # 判断手机号重复
            $phoneInfo = Db::table('member')->field('id')->where("phone='" . $info['phone'] . "' and code != '" . $code . "'")->find();
            if (!empty($phoneInfo)) {
                return array('status' => false, 'msg' => '手机号重复');
            }
            # 修改基本信息
            # 头像图片处理
            if (empty($info['head_portrait'])) {
                unset($info['head_portrait']);
            } else {
                ResourceService::delCacheItem($info['head_portrait']);
            }
            # 身份证图片处理
            if (empty($info['idcard'])) {
                unset($info['idcard']);
            } else {
                ResourceService::delCacheItem($info['idcard']);
            }
            # 支付宝收款码
            if (empty($collection['ali_img'])) {
                unset($collection['ali_img']);
            } else {
                ResourceService::delCacheItem($collection['ali_img']);
            }
            # 微信收款码
            if (empty($collection['wx_img'])) {
                unset($collection['wx_img']);
            } else {
                ResourceService::delCacheItem($collection['wx_img']);
            }
            # 银联收款码
            if (empty($collection['union_img'])) {
                unset($collection['union_img']);
            } else {
                ResourceService::delCacheItem($collection['union_img']);
            }
            # 删除无用图片
            ResourceService::delUploadCache();
            # 修改用户信息
            Db::table('member')->where(array('code' => $code))->update($info);
            if ($info['team_id'] != $old_teamId) {
                # 说明修改了团队 , 要修改团队人数
                # 原团队人数减一
                Db::table('team')->where(array('id' => $old_teamId))->setDec('team_num');
                # 新团队人数加一
                Db::table('team')->where(array('id' => $info['team_id']))->setInc('team_num');
            }
            # 修改收款信息
            Db::table('member_collection')->where(array('member_code' => $code))->update($collection);
            $collectionID = Db::table('member_collection')->where(array('member_code' => $code))->find();
            if (empty($collectionID)) {
                $collection['member_code'] = $code;
                Db::table('member_collection')->insert($collection);
            }
            # 修改财产信息
            Db::table('member_property')->where(array('member_code' => $code, 'is_fake' => 1))->update($property);
            $propertyID = Db::table('member_property')->where(array('member_code' => $code, 'is_fake' => 1))->find();
            if (empty($propertyID)) {
                $property['member_code'] = $code;
                Db::table('member_property')->insert($property);
            }
            # 查询生意ID
            $businessID = Db::table('member_business_grid')->where(array('member_code' => $code))->find();
            if (empty($businessID)) {
                # 添加生意格子信息
                $gridInfo = array();
                for ($i = 1; $i <= 12; $i++) {
                    array_push($gridInfo, array('grid' => $i, 'member_code' => $code));
                }
                Db::table('member_business_grid')->insertAll($gridInfo);
            }
            # 判断是否需要添加记录
            if ($property['income'] != $property_old['income']) {
                # 添加收益修改记录
                $change_income = floatval($property['income']) - floatval($property_old['income']);
                MemberService::addLog_income($code, $change_income, -1);
            }
            if ($property['integral'] != $property_old['integral']) {
                # 添加积分修改记录
                $change_integral = floatval($property['integral']) - floatval($property_old['integral']);
                if ($change_integral > 0) {
                    $status = 1;
                } else {
                    $status = 2;
                }
                MemberService::addLog_integral($code, $change_integral, $status, -1);
            }
            if ($property['gold'] != $property_old['gold']) {
                # 添加金币修改记录
                $change_gold = intval($property['gold']) - intval($property_old['gold']);
                MemberService::addLog_gold($code, $change_gold, -1);
            }
            if ($property['materials'] != $property_old['materials']) {
                # 添加材料修改记录
                $change_materials = floatval($property['materials']) - floatval($property_old['materials']);
                MemberService::addLog_materials($code, $change_materials, -1);
            }
            # 修改redis
            MemberService::changeRedis($code);
            return array('status' => true);
        }
    }


    /**
     * @return mixed
     * @content 用户信息加载页面
     */
    function memberInfo()
    {
        $memberCode = input('get.memberCode');
        $team_id = input('get.team_id');
        $view = input('get.view');
        if (!empty($memberCode) and !empty($view)) {
//            if (empty($team_id))
            $this->assign('memberCode', $memberCode);
            $this->assign('team_id', $team_id);
            return $this->fetch('/member/' . $view);
        }
    }

    /**
     * @content 删除session无用图片
     */
    function clearSession()
    {
        ResourceService::delUploadCache();
    }

    /**
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 收益记录
     */
    function incomeLog()
    {
        $memberCode = input('post.memberCode');
        # 定义listRows
        $listRows = input('post.limit');
        if (empty($listRows)) {
            $listRows = 1;
        }
        # 定义where
        $_where = "member_code = '" . $memberCode . "' and type != -1";
        # 搜索条件
        $searchParams = json_decode(input('post.searchParams'), true);
        if (!empty($searchParams)) {
            # 时间筛选
            if (!empty($searchParams['searchTime_min'])) {
                $_where .= " and date(create_time) >= '" . $searchParams['searchTime_min'] . "'";
            }
            if (!empty($searchParams['searchTime_max'])) {
                $_where .= " and date(create_time) <= '" . $searchParams['searchTime_max'] . "'";
            }
            # 类型筛选
            if (!empty($searchParams['type'])) {
                $_where .= " and type = " . $searchParams['type'];
            }
        }
        # 查询信息
        $field = 'income,type,create_time';
        $info = MemberService::logInfo('log_earn', $field, $_where, array('id' => 'desc'), true, $listRows, request()->param());
        return $this->jsonSuccessData($info);
    }

    /**
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 金币记录
     */
    function goldLog()
    {
        $memberCode = input('post.memberCode');
        # 定义listRows
        $listRows = input('post.limit');
        if (empty($listRows)) {
            $listRows = 1;
        }
        # 定义where
        $_where = "member_code = '" . $memberCode . "' and type != -1";
        # 搜索条件
        $searchParams = json_decode(input('post.searchParams'), true);
        if (!empty($searchParams)) {
            # 时间筛选
            if (!empty($searchParams['searchTime_min'])) {
                $_where .= " and date(create_time) >= '" . $searchParams['searchTime_min'] . "'";
            }
            if (!empty($searchParams['searchTime_max'])) {
                $_where .= " and date(create_time) <= '" . $searchParams['searchTime_max'] . "'";
            }
            # 类型筛选
            if (!empty($searchParams['type'])) {
                $_where .= " and type = " . $searchParams['type'];
            }
            # 支出/收入筛选
            if (!empty($searchParams['status'])) {
                if ($searchParams['status'] == 1) {
                    # 支出
                    $_where .= " and type in (1,8,9,10)";
                } else {
                    # 收入
                    $_where .= " and type in (2,3,4,5,6,7)";
                }
            }
        }
        # 查询信息
        $field = 'gold_num,type,create_time,memberp_code,(select name from member where code=memberp_code) pCode,type_branch';
        $info = MemberService::logInfo('log_gold', $field, $_where, array('id' => 'desc'), true, $listRows, request()->param());
        return $this->jsonSuccessData($info);
    }

    /**
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 积分记录
     */
    function integralLog()
    {
        $memberCode = input('post.memberCode');
        # 定义listRows
        $listRows = input('post.limit');
        if (empty($listRows)) {
            $listRows = 1;
        }
        # 定义where
        $_where = "member_code = '" . $memberCode . "' and type != -1";
        # 搜索条件
        $searchParams = json_decode(input('post.searchParams'), true);
        if (!empty($searchParams)) {
            # 时间筛选
            if (!empty($searchParams['searchTime_min'])) {
                $_where .= " and date(create_time) >= '" . $searchParams['searchTime_min'] . "'";
            }
            if (!empty($searchParams['searchTime_max'])) {
                $_where .= " and date(create_time) <= '" . $searchParams['searchTime_max'] . "'";
            }
            # 类型筛选
            if (!empty($searchParams['type'])) {
                $_where .= " and type = " . $searchParams['type'];
            }
            # 支出/收入筛选
            if (!empty($searchParams['status'])) {
                $_where .= " and status = " . $searchParams['status'];
            }
        }
        # 查询信息
        $field = 'num,type,status,create_time,memberp_code,(select name from member where code=memberp_code) pCode,type_branch';
        $info = MemberService::logInfo('log_integral', $field, $_where, array('id' => 'desc'), true, $listRows, request()->param());
        return $this->jsonSuccessData($info);
    }

    /**
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 交易记录/详情
     */
    function tradLog()
    {
        if (input('get.action') != 'detail') {
            # 用户交易记录
            $memberCode = input('post.memberCode');
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 1;
            }
            # 定义where
            $_where = "seller_code = '" . $memberCode . "' or buyer_code = '" . $memberCode . "'";
            # 搜索条件
            $searchParams = json_decode(input('post.searchParams'), true);
            if (!empty($searchParams)) {
                # 类型筛选
                if (!empty($searchParams['type'])) {
                    if ($searchParams['type'] == 1) {
                        # 出售
                        $_where = "seller_code = '" . $memberCode . "'";
                    } else {
                        # 购进
                        $_where = "buyer_code = '" . $memberCode . "'";
                    }
                }
            }
            # 查询信息
            $field = 'id,industry_imgurl imgurl,industry_title title,buy_time,sell_time,if(seller_code="' . $memberCode . '",1,2) type';
            $info = MemberService::logInfo('log_trad', $field, $_where, array('id' => 'desc'), true, $listRows, request()->param());
            return $this->jsonSuccessData($info);
        } else {
            # 交易记录详情
            $id = input('get.id');
            # 查询详情
            $info = Db::table('log_trad lt')
                ->field('lt.*,i.desc,i.day_rent,i.detail')
                ->join('industry i', 'i.id=lt.id', 'left')
                ->where(array('lt.id' => $id))
                ->find();
            # 类型(1 出售 2 购进)
            $mark = input('get.mark');
            $this->assign('mark', $mark);
            # 查询买/卖家信息
            if ($mark == 1) {
                # 出售  查询买家信息
                $code = $info['buyer_code'];
            } else {
                # 购进  查询卖家信息
                $code = $info['seller_code'];
            }
            $memberInfo = Db::table('member m')
                ->field('m.code,m.name,m.phone,m.head_portrait,mc.wx_number,mc.ali_number,mc.unionpay_number,ml.title')
                ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                ->join('member_level ml', 'ml.level=m.level', 'left')
                ->where(array('code' => $code))->find();
            $this->assign('memberInfo', $memberInfo);
            $this->assign('info', $info);
            return $this->fetch('/member/tradDetail');
        }
    }

    /**
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 用户卡券
     */
    function voucherInfo()
    {
        $memberCode = input('post.memberCode');
        # 定义listRows
        $listRows = input('post.limit');
        if (empty($listRows)) {
            $listRows = 1;
        }
        # 定义where
        $_where = "member_code = '" . $memberCode . "' and use_status=1";
        # 搜索条件
        $searchParams = json_decode(input('post.searchParams'), true);
        if (!empty($searchParams)) {
            # 名称筛选
            if (!empty($searchParams['title'])) {
                $_where .= " and voucher_title like '%" . $searchParams['title'] . "%'";
            }
        }
        # 查询信息
        $field = '*';
        $info = MemberService::logInfo('member_voucher', $field, $_where, array('id' => 'desc'), true, $listRows, request()->param());
        return $this->jsonSuccessData(array('info' => $info, 'code' => $memberCode));
    }

    /**
     * @return mixed|string
     * @throws \think\exception\DbException
     * @content 赠送卡券
     */
    function giveVoucher()
    {
        if (input('get.action') == 'view') {
            # 加载页面
            $memberCode = input('get.code');
            $this->assign('memberCode', $memberCode);
            return $this->fetch('/member/giveVoucher');
        }
        if (input('get.action') == 'ajax') {
            # 执行添加
            $arr = array();
            $info = input('post.');
            $info['expiration_time'] = date('Y-m-d H:i:s', strtotime('+ ' . $info['expiration'] . ' days'));
            $info['get_time'] = date("Y-m-d H:i:s");
            $num = $info['num'];
            unset($info['expiration'], $info['num']);
            for ($i = 0; $i < $num; $i++) {
                array_push($arr, $info);
            }
            if (!empty($arr)) {
                Db::table('member_voucher')->insertAll($arr);
                return array('status' => true);
            } else {
                return array('status' => false, 'msg' => '添加信息为空');
            }

        }
        if (input('get.action') == 'voucher') {
            # 查询卡券列表
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 10;
            }
            # where 条件
            $where = '';
            # 名称搜索
            $title = input('post.title');
            if (!empty($title)) {
                $where = "title like '%" . $title . "%'";
            }
            # 查询信息
            $info = Db::table('voucher')
                ->field('id,title,price,explain')
                ->where($where)
                ->order(array('id' => 'desc'))
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($info);
        }
    }

    /**
     * @return array|string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 用户生意/删除
     */
    function businessInfo()
    {
        if (input('get.action') == 'delete') {
            # 执行删除操作
            $id = input('post.id');
            $info = Db::table('member_business')->where(array('id' => $id))->find();
            $_redis = new Redis();
            if ($info['status'] == 3) {
                $sale_array = $_redis->hGetJson("member_sale_bussiness", $info['earnings_level']);
                if (!empty($sale_array)) {
                    foreach ($sale_array as $k => $v) {
                        if ($v['id'] == $id) {
                            unset($sale_array[$k]);
                            break;
                        }
                    }
                    $_redis->hSetJson("member_sale_bussiness", $info['earnings_level'], array_values($sale_array));
                }
            }
            if ($info['place_status'] == 1) {
                // 删除栏位
                # 查询栏位号
                $_business = Db::table("member_business_grid")->where(array("member_business_id" => $id))->find();
                if (!empty($_business)) {
                    Db::table("member_business_grid")->where(array("id" => $_business['id']))->update(array("member_business_id" => 0, "status" => 1));
                    $_business_list = $_redis->hGetJson("member_business", $info['member_code']);
                    if (!empty($_business_list)) {
                        $_business_list[$_business['grid'] - 1] = array("mbg_id"=>$_business_list[$_business['grid'] - 1]['mbg_id'],"member_business_id" => 0, "status" => 1, "open_status" => 1, "grid" => $_business['grid']);
                        $_redis->hSetJson("member_business", $info['member_code'], $_business_list);
                    }
                }
            }
            $res = Db::table('member_business')->where(array('id' => $id))->update(array('status' => -1,"settlement_status"=>3));
            if ($res) {
                return array('status' => true);
            } else {
                return array('status' => false, 'msg' => '删除失败');
            }
        } elseif (input('get.action') == 'confimTrade') {
            # 资产确认交易
            $id = input('post.id');// 玩家生意id
            $data = Db::table("trad_audit")->where(array("industry_id" => $id, "is_violations" => 1, "trad_status" => 1))->find();
            if (!empty($data)) {
                $data['sell_id'] = $id;
                $jobService = new jobService();
                $res = $jobService->successTrade($data);
                if ($res['status']) {
                    return array("status" => true);
                } else {
                    return array("status" => false, "交易失败");
                }
            } else {
                return array("status" => false, "msg" => "该生意不可交易");
            }
        } else {
            $memberCode = input('post.memberCode');
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 1;
            }
            # 定义where
            $_where = "mbg.member_code = '" . $memberCode . "'";
            $status = input("post.status");
            if (!empty($status)) {
                $_where .= " and mb.status = {$status}";
            }
            # 搜索条件
            $searchParams = json_decode(input('post.searchParams'), true);
            if (!empty($searchParams)) {
                # 名称筛选
                if (!empty($searchParams['title'])) {
                    $_where .= " and industry_title like '%" . $searchParams['title'] . "%'";
                }
            }
            # 查询信息
//            $info = Db::table('member_business mb')
////                ->field('mb.id,mb.industry_title,ml.title,buy_time,buy_price,growth_cycle,earnings_price,earnings_ratio,sell_time,status,buy_price,sale_price')
////                ->join('member_level ml', 'mb.earnings_level=ml.level', 'left')
////                ->where($_where)
////                ->order(array("status" => 'desc', 'mb.id' => 'desc'))
////                ->paginate($listRows, false, ['query' => request()->param()]);
            $info = Db::table("member_business_grid mbg")
                ->field("mbg.grid,mbg.status open_status,mb.id,mb.status,mb.industry_title,mb.buy_time,mb.growth_cycle,mb.earnings_price,mb.earnings_ratio,
                mb.sell_time,mb.buy_price,mb.sale_price,mb.lanunch,mbg.member_code")
                ->join("member_business mb","mbg.member_business_id = mb.id","left")
                ->where($_where)
                ->paginate(12, false, ['query' => request()->param()]);
            return $this->jsonSuccessData(array('info' => $info, 'code' => $memberCode));
        }
    }

    /**
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 仓库生意列表
     *
     */
    function wareInfo()
    {
        if (input('get.action') == 'delete') {
            # 执行删除操作
            $id = input('post.id');
            $info = Db::table('member_business')->where(array('id' => $id))->find();
            $_redis = new Redis();
            if ($info['status'] == 3) {
                $sale_array = $_redis->hGetJson("member_sale_bussiness", $info['earnings_level']);
                if (!empty($sale_array)) {
                    foreach ($sale_array as $k => $v) {
                        if ($v['id'] == $id) {
                            unset($sale_array[$k]);
                            break;
                        }
                    }
                    $_redis->hSetJson("member_sale_bussiness", $info['earnings_level'], array_values($sale_array));
                }
            }
             // 删除仓库
             $_redis->hDel("wareHouse", $info['member_code']);
            $res = Db::table('member_business')->where(array('id' => $id))->update(array('status' => -1,"settlement_status"=>3));
            if ($res) {
                return array('status' => true);
            } else {
                return array('status' => false, 'msg' => '删除失败');
            }
        } elseif (input('get.action') == 'confimTrade') {
            # 资产确认交易
            $id = input('post.id');// 玩家生意id
            $data = Db::table("trad_audit")->where(array("industry_id" => $id, "is_violations" => 1, "trad_status" => 1))->find();
            if (!empty($data)) {
                $data['sell_id'] = $id;
                $jobService = new jobService();
                $res = $jobService->successTrade($data);
                if ($res['status']) {
                    return array("status" => true);
                } else {
                    return array("status" => false, "交易失败");
                }
            } else {
                return array("status" => false, "msg" => "该生意不可交易");
            }
        } else {
            $memberCode = input('post.memberCode');
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 1;
            }
            # 定义where
            $_where = "member_code = '" . $memberCode . "' and mb.status!=-1 and place_status=2 ";
            $status = input("post.status");
            if (!empty($status)) {
                $_where .= " and mb.status = {$status}";
            }
            # 搜索条件
            $searchParams = json_decode(input('post.searchParams'), true);
            if (!empty($searchParams)) {
                # 名称筛选
                if (!empty($searchParams['title'])) {
                    $_where .= " and industry_title like '%" . $searchParams['title'] . "%'";
                }
            }
            # 查询信息
            $info = Db::table('member_business mb')
                ->field('mb.id,mb.industry_title,ml.title,buy_time,buy_price,growth_cycle,earnings_price,earnings_ratio,sell_time,status,buy_price,sale_price')
                ->join('member_level ml', 'mb.earnings_level=ml.level', 'left')
                ->where($_where)
                ->order(array("status" => 'desc', 'mb.id' => 'desc'))
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData(array('info' => $info, 'code' => $memberCode));
        }
    }
    /**
     * @return array|mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 赠送资产
     */
    function giveBusiness()
    {
        if (input('get.action') == 'view') {
            # 加载页面
            $memberCode = input('get.code');
            $this->assign('memberCode', $memberCode);
            return $this->fetch('/member/giveBusiness');
        }
        if (input('get.action') == 'ajax') {
            # 执行赠送
            $info = input('post.');
            # 查询行业最大价值
            $indu_info = Db::table("industry")->field('max_worth')->where(array("id" => $info['industry_id']))->find();
            if ($info['buy_price'] >= $indu_info['max_worth']) {
                $info['status'] = 2;
                $info['sale_price'] = $info['buy_price'];
            } else {
                $info['sale_price'] = $info['buy_price'] + ($info['buy_price'] * $info['day_income']);
            }
            $info['buy_time'] = date("Y-m-d H:i:s");
            $info['earnings_ratio'] = $info['day_income'];
            $info['day_income'] = priceFormat($info['buy_price'] * $info['day_income'] / $info['growth_cycle']);
            $info['day_rents'] = $info['day_income'] * $info['day_rent'];
            $info['earnings_price'] = priceFormat($info['sale_price']);
            unset($info['day_rent']);
            $redis = new Redis();
            # 判断是否有空格子,没有放仓库
            $member_business_grid = Db::table("member_business_grid")->where("member_business_id=0 and status=1 and member_code='" . $info['member_code'] . "'")->find();
            if (!empty($member_business_grid)) {
                $info['sell_time'] = date('Y-m-d H:i:s', strtotime('+ ' . $info['growth_cycle'] . 'days'));
                $info['opera_start_time'] = date('Y-m-d H:i:s');
                $info['place_status'] = 1;
                $businessId = Db::table('member_business')->insertGetId($info);
                # 修改格子信息
                $res = Db::table("member_business_grid")->where(array("id" => $member_business_grid['id']))->update(array("member_business_id" => $businessId));
                $list = $redis->hGetJson("member_business", $info['member_code']);
                if (!empty($list)) {
                    $new_business = Db::table("member_business")->where(array("id" => $businessId))->find();
                    $list[$member_business_grid['grid'] - 1]['member_business_id'] = $businessId;
                    $list[$member_business_grid['grid'] - 1] = array_merge($list[$member_business_grid['grid'] - 1], $new_business);
                    $redis->hSetJson("member_business", $info['member_code'], $list);
                }
            } else {
                $info['place_status'] = 2;
                $businessId = Db::table('member_business')->insertGetId($info);
                $list = $redis->hDel("wareHouse", $info['member_code']);
            }
            # 更改用户赠送生意状态
            Db::table("member")->where(array("code" => $info['member_code']))->update(array("giving_status" => 2));
            # 给用户发送消息
            $news = new IGeTuiService();
            $news->pushMessageToSingle("生意到账了", "生意到账提醒", "云盟时代赠送给您的生意‘" . $info['industry_title'] . "’已到账，请注意查收", $info['member_code'], 2);
            return array('status' => true);
        }
        if (input('get.action') == 'business') {
            # 查询行业列表
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 10;
            }
            # where 条件
            $where = 'i.is_del=2 and i.status=1';
            # 名称搜索
            $title = input('post.title');
            if (!empty($title)) {
                $where .= "title like '%" . $title . "%'";
            }
            # 查询信息
            $info = Db::table('industry i')
                ->field('i.id,i.title,i.level,ml.title levelTitle,day_rent,i.logo,i.day_rent')
                ->join('member_level ml', 'i.level=ml.level', 'left')
                ->where($where)
                ->order(array('id' => 'desc'))
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($info);
        }
        if (input('get.action') == 'businessCycle') {
            # 查询收益周期
            $industryId = input('post.industryId');
            $info = Db::table('industry_cycleincome')->where(array('industry_id' => $industryId))->order(array('id' => 'asc'))->select();
            return $this->jsonSuccessData(array('info' => $info, 'total' => count($info)));
        }
    }

    /**
     * @return string
     * @throws \think\exception\DbException
     * @content 查看玩家团队
     */
    function memberTeam()
    {
        # 接收用户ID
        $memberCode = input('post.memberCode');
        $team_id = input('post.team_id');
        # 定义listRows
        $listRows = input('post.limit');
        if (empty($listRows)) {
            $listRows = 1;
        }
        # 定义where
        $_where = "team_id = '" . $team_id . "'";
        if (!empty($memberCode)) {
            $_where = "p_code = '" . $memberCode . "'";
        }
        # 搜索条件
        $searchParams = json_decode(input('post.searchParams'), true);
        if (!empty($searchParams)) {
            # 名称/手机号筛选
            if (!empty($searchParams['searchInfo'])) {
                $_where .= " and name like '%" . $searchParams['searchInfo'] . "%' or  phone like '%" . $searchParams['searchInfo'] . "%'";
            }
            # 地区筛选
            if (!empty($searchParams['province'])) {
                $_where .= " and m.province='" . $searchParams['province'] . "'";
            }
            if (!empty($searchParams['city'])) {
                $_where .= " and m.city='" . $searchParams['city'] . "'";
            }
            if (!empty($searchParams['area'])) {
                $_where .= " and m.area='" . $searchParams['area'] . "'";
            }
        }
        # 查询信息
        $info = Db::table('member m')
            ->field('m.code,m.head_portrait,m.phone,m.name,m.address,(select count(id) from member where p_code = m.code and status = 5 and fictitious != 1) team_num,mp.income team_earnings')
            ->join('member_property mp','mp.member_code=m.code','left')
            ->join('team t', 'm.team_id=t.id and t.is_fake=1', 'left')
            ->where("m.fictitious != 1")
            ->where($_where)
            ->paginate($listRows, false, ['query' => request()->param()]);
        return $this->jsonSuccessData($info);
    }
}